source("Code/silent.R")

# We do not want to keep intermediate objects around (env would get too large):
source_temp <- function(file) {
  local_env <- new.env()
  source(file, local = local_env)
}

if (!file.exists("Data/Saves/full_mortality_data_2015_2021_no_2019_second_semester_2020_first_semester.rds")) {
  message("Running vb_preprocess.R to generate full mortality data...")
  silent(source_temp("Code/vb_preprocess.R"))
} else {
  message("Found preprocessed mortality data, skipping preprocessing...")
}

if (!file.exists("Data/Saves/electoral_stability_municipality_level_vb_no_2020_2.rds")) {
  message("Running vb_estimate.R to estimate excess hazard...")
  silent(source_temp("Code/vb_estimate.R.R"))
  Sys.sleep(30) # Allow time for file system operations to complete
} else {
  message("Found excess hazard estimates, not re-estimating...")
}

# After estimate_yearly_excess_hazard_no_2020_vb2.R
if (!file.exists("Data/Saves/electoral_stability_municipality_level_vb_no_2020_2.rds")) {
  stop("Error: Excess hazard results file was not created properly, please try running the script again manually.")
}

message("Running vb_postprocess.R to export estimation results...")
source_temp("Code/vb_postprocess.R")